<?php

namespace App\Http\Controllers\Admin\Tags\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Tags;
use DB;
use Illuminate\Support\Facades\Redis;

class TagsApi extends Controller
{   
    /**
     * 获取标签列表
     * @return [array] [标签列表信息]
     */
    public static function getTagsList()
    {

        if (Redis::keys('tags-list')) {

            return json_decode(Redis::get('tags-list'), true);
        }

        $tagsList = Tags::all()->toArray();

        Redis::set('tags-list', json_encode($tagsList));

        return $tagsList;
    }

    /**
     * 执行新增标签
     * @param  [string] $tagName [标签名]
     * @return [json]          [执行后的信息]
     */
    public static function tagsStore($tagName)
    {   

        $tagModel = new Tags;
        $tagModel->name = $tagName;
        $bool = $tagModel->save();

        if ($bool) {

            $result = [
                'code' => 200,
                'msg' => '添加成功',
                'content' => $tagModel,
            ];

            return response()->json($result);
        } else {

            $result = [
                'code' => 400,
                'msg' => '添加失败',
            ];

            return response()->json($result);
        }
    }

    /**
     * 执行删除某一个标签
     * @param  [number] $id [要删除的标签ID]
     * @return [json]     [执行删除后的信息]
     */
    public static function tagsDel($id)
    {      
        //查找标签ID是否已经属于某个文章
        $relation = DB::table('articles_tags')->select('tag_id')->where('tag_id', $id)->limit(1)->first();
        // return response()->json($relation);
        if ($relation) {
            $result = [
                'code' => 300,
                'msg' => '该标签ID已经属于某个文章,无法删除',
            ];
            return response()->json($result);
        }

        //执行删除
        $bool = Tags::destroy($id);

        if ($bool) {
            $result = [
                'code' => 200,
                'msg' => '删除标签成功',
            ];

            return response()->json($result);

        } else {
            $result = [
                'code' => 400,
                'msg' => '删除标签失败',
            ];

            return response()->json($result);
        }

    }

    /**
     * 获取某一个标签的信息
     * @param  [number] $id [要获取的标签的ID]
     * @return [array]     [标签的信息]
     */
    public static function getTagInfo($id)
    {
        $tagInfo = Tags::find($id)->toArray();

        return $tagInfo;
    }


    public static function tagsUpdate(Request $request, $id)
    {   
        $tagModel = Tags::find($id);
        $tagModel->name = $request->input('name');
        $bool = $tagModel->save();

        if ($bool) {

            $result = [
                'code' => 200,
                'msg' => '修改标签成功',
            ];

            return $result;
        } else {

            $result = [
                'code' => 400,
                'msg' => '修改标签失败',
            ];

            return $result;
        }
    }


}
